<template>
  <div class="notice-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-bar">
      <div class="search-group">
        <el-input
          v-model="searchParams.keyword"
          placeholder="输入姓名/失踪地点"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon class="search-icon"><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="searchParams.status"
          placeholder="全部状态"
          clearable
          class="status-select"
          @change="handleSearch"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-button
          type="danger"
          :icon="Search"
          class="search-btn"
          @click="handleSearch"
        >
          搜索
        </el-button>
      </div>

      <el-button
        type="danger"
        :icon="Plus"
        class="create-btn"
        @click="handleCreate"
      >
        新建启事
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="noticeList"
        v-loading="loading"
        style="width: 100%"
        stripe
        highlight-current-row
        :header-cell-style="{ position: 'sticky', top: '0', zIndex: '10',}"
        height="550"
      >
        <el-table-column prop="cover" label="照片" width="120" align="center">
          <template #default="{ row }">
            <el-image
              :src="row.cover"
              :preview-src-list="[row.cover]"
              fit="cover"
              class="cover-image"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="姓名" width="120" sortable>
          <template #header>
            <span class="column-header">姓名</span>
          </template>
        </el-table-column>

        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.gender === '男' ? 'danger' : 'warning'"
              effect="dark"
              class="gender-tag"
            >
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="age" label="年龄" width="100" sortable />

        <el-table-column prop="missingTime" label="失踪时间" width="180" sortable />

        <el-table-column prop="missingLocation" label="失踪地点" min-width="200" />

        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="statusStyleMap[row.status].type"
              :effect="row.status === 'published' ? 'dark' : 'plain'"
              class="status-tag"
            >
              {{ statusStyleMap[row.status].label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleEdit(row.id)"
            >
              编辑
            </el-button>

            <el-dropdown trigger="click" @command="handleCommand(row, $event)">
              <el-button type="danger" size="small" plain>
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="action in rowActions"
                    :key="action.command"
                    :command="action.command"
                    :divided="action.divided"
                  >
                    <component :is="action.icon" v-if="action.icon" />
                    <span :class="action.danger ? 'danger-action' : ''">
                      {{ action.label }}
                    </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialog.visible"
      title="删除确认"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="delete-content">
        <el-icon color="#ff4d4f" :size="24"><Warning /></el-icon>
        <span class="delete-text">确定要永久删除该寻人启事吗？此操作不可恢复！</span>
      </div>
      <template #footer>
        <el-button @click="deleteDialog.visible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search,
  Plus,
  ArrowDown,
  Warning,
  Picture
} from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";

// 类型定义
interface NoticeItem {
  id: string
  cover: string
  name: string
  gender: '男' | '女'
  age: number
  missingTime: string
  missingLocation: string
  status: 'draft' | 'published' | 'closed'
}

interface StatusStyle {
  type: 'success' | 'info' | 'warning' | 'danger'
  label: string
}

// 常量定义
const statusOptions = [
  { value: 'draft', label: '草稿' },
  { value: 'published', label: '已发布' },
  { value: 'closed', label: '已关闭' }
]

const statusStyleMap: Record<string, StatusStyle> = {
  draft: { type: 'info', label: '草稿' },
  published: { type: 'danger', label: '已发布' },
  closed: { type: 'warning', label: '已关闭' }
}

const rowActions = [
  { command: 'publish', label: '发布', icon: 'upload' },
  { command: 'close', label: '关闭', icon: 'switch' },
  { command: 'delete', label: '删除', icon: 'delete', divided: true, danger: true }
]

// 响应式数据
const loading = ref(false)
const noticeList = ref<NoticeItem[]>([])
const searchParams = reactive({
  keyword: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const deleteDialog = reactive({
  visible: false,
  currentId: ''
})

// 获取路由实例
const router = useRouter();

// 模拟数据
const mockData: NoticeItem[] = Array.from({ length: 35 }, (_, i) => ({
  id: `${i + 1}`,
  cover: `https://picsum.photos/100/100?random=${i}`,
  name: `失踪者${i + 1}`,
  gender: i % 2 === 0 ? '男' : '女',
  age: Math.floor(Math.random() * 50) + 10,
  missingTime: `2023-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
  missingLocation: ['北京', '上海', '广州', '深圳', '成都'][i % 5] + '某地点',
  status: ['draft', 'published', 'closed'][i % 3] as 'draft' | 'published' | 'closed'
}))

// 生命周期
onMounted(() => {
  loadData()
})

// 方法
const loadData = async () => {
  try {
    loading.value = true
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))

    // 过滤数据
    let data = mockData.filter(item => {
      const keywordMatch = searchParams.keyword
        ? item.name.includes(searchParams.keyword) ||
        item.missingLocation.includes(searchParams.keyword)
        : true
      const statusMatch = searchParams.status ? item.status === searchParams.status : true
      return keywordMatch && statusMatch
    })

    // 分页处理
    const start = (pagination.current - 1) * pagination.size
    const end = start + pagination.size
    noticeList.value = data.slice(start, end)
    pagination.total = data.length
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleCreate = () => {
  // 跳转到新建启事页面，不带参数
  router.push('/publish-search/create-notice');
}

const handleEdit = (id: string) => {
  // 跳转到新建启事页面，不带参数
  router.push('/publish-search/create-notice');
}

const handleCommand = (row: NoticeItem, command: string) => {
  switch (command) {
    case 'publish':
      updateStatus(row.id, 'published')
      break
    case 'close':
      updateStatus(row.id, 'closed')
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

const handleDelete = (row: NoticeItem) => {
  deleteDialog.currentId = row.id
  deleteDialog.visible = true
}

const confirmDelete = async () => {
  try {
    // 模拟删除请求
    await new Promise(resolve => setTimeout(resolve, 500))
    noticeList.value = noticeList.value.filter(item => item.id !== deleteDialog.currentId)
    ElMessage.success('删除成功')
    deleteDialog.visible = false
    loadData() // 重新加载数据
  } catch (err) {
    ElMessage.error('删除失败')
  }
}

const updateStatus = async (id: string, status: NoticeItem['status']) => {
  try {
    // 模拟状态更新请求
    await new Promise(resolve => setTimeout(resolve, 300))
    const index = noticeList.value.findIndex(item => item.id === id)
    if (index !== -1) {
      noticeList.value[index].status = status
      ElMessage.success('状态更新成功')
    }
  } catch (err) {
    ElMessage.error('状态更新失败')
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadData()
}
</script>

<style lang="scss" scoped>
.notice-management {
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;

    .search-group {
      display: flex;
      align-items: center;
      gap: 12px;

      .search-input {
        width: 280px;
      }

      .status-select {
        width: 120px;
      }

      .search-btn {
        padding: 10px 20px;
      }
    }

    .create-btn {
      padding: 10px 24px;
    }
  }

  .cover-image {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.2);
      cursor: zoom-in;
    }
  }

  .image-error {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
  }

  .column-header {
    font-weight: 600;
  }

  .gender-tag {
    font-weight: 500;
    letter-spacing: 1px;
  }

  .status-tag {
    font-weight: 500;
    min-width: 60px;
    text-align: center;
  }

  .pagination-wrapper {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
  }

  .delete-content {
    display: flex;
    align-items: center;
    gap: 12px;

    .delete-text {
      font-size: 15px;
    }
  }
}

// 覆盖Element Plus默认样式
:deep(.el-pagination.is-background) {
  --el-color-primary: #ff4d4f;

  button:hover {
    color: #ff4d4f;
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  &:hover {
    color: #ff4d4f;
  }
}

</style>
